package com.javid.study.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.javid.study.mapper.NynInfoMapper;
import com.javid.study.mapper.NynPokerMapper;
import com.javid.study.pojo.NynInfo;
import com.javid.study.pojo.NynPoker;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

@Service
public class InitService {

    @Autowired
    NynPokerMapper nynPokerMapper;
    @Autowired
    NynInfoMapper nynInfoMapper;
    @Autowired
    RedisTemplate<String,String> redisTemplate;

    public boolean init(String inputName) {
        String[] nameList = inputName.split("，");
        for (int i = 0; i < nameList.length; i++) {
            nameList[i] = nameList[i];
        }
        if (nameList.length > 9 || nameList.length < 2) {
            return false;
        }
        this.initPoker();
        redisTemplate.opsForValue().set("whohask", "");
        redisTemplate.opsForValue().set("whohas2", "");
        this.initPlayer(nameList);
        return true;
    }

    // 初始化poker
    public boolean initPoker() {
        try {
            UpdateWrapper<NynPoker> wrapper = new UpdateWrapper<>();
            wrapper.set("playerid", 0);
            wrapper.set("used", 0);
            redisTemplate.opsForValue().set("lastpoker", "");
            nynPokerMapper.update(null, wrapper);
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    // 初始化玩家
    public void initPlayer(String[] nameList) {
        // 更新上轮玩家状态
        UpdateWrapper<NynInfo> wrapper = new UpdateWrapper<>();
        wrapper.set("isdelete", 1);
        nynInfoMapper.update(null, wrapper);
        // 插入本轮玩家
        for (int i = 0; i < nameList.length; i++) {
            NynInfo info = new NynInfo();
            info.setPlayerid(i+1);
            info.setName(nameList[i]);
            nynInfoMapper.insert(info);
        }
        // 更新now
        redisTemplate.opsForValue().set("now", "1");
    }

    public void onemore(){
        this.initPoker();
        LambdaQueryWrapper<NynInfo> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(NynInfo::getIsdelete, 0);
        NynInfo info = new NynInfo();
        info.setHasdrinked(0);
        info.setNeeddrink(0);
        redisTemplate.opsForValue().set("now", "1");
        redisTemplate.opsForValue().set("whohask", "");
        redisTemplate.opsForValue().set("whohas2", "");
        nynInfoMapper.update(info, wrapper);
    }
}
